// miniprogram/pages/shopcart/shopcart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

    shopcartData:[],
    allSelect:false,
    isManage:false,
    total:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
   
  },
  onShow:function(){

    
    this.getShopcartByUser()
    
  },

  getShopcartByUser:function(){

    wx.showLoading({
      title: '加载中...',
    })

    wx.cloud.callFunction({
      name:'get_shopcart_buyuser',
      success:res=>{
        // console.log('res=>',res)
        wx.hideLoading()


        var ids = []

        res.result.data.forEach(v=>{

          if(ids.indexOf(v.id)===-1){
            ids.push(v.id)
          }

          

        })


        this.setData({
          shopcartData:res.result.data,
          
        })

        this.getProductInfo(ids)


      },
      fail:error=>{
        console.log("云函数调用失败",error)
        wx.hideLoading()
      }
    })

  },
  getProductInfo:function(ids){

    wx.showLoading({
      title: '加载中...',
    })

    wx.cloud.callFunction({
      name:'get_product_byid',
      data:{
        ids:ids
      },
      success:res=>{
        wx.hideLoading()
        // console.log('获取商品信息res=>',res)
        var shopcartData = this.data.shopcartData
        var total = 0
        shopcartData.forEach(v=>{

          for(var i = 0; i < res.result.data.length ; i++){

            if(res.result.data[i]._id === v.id){

              v.img = res.result.data[i].small_img

              v.price = res.result.data[i].price

              v.name = res.result.data[i].name
            }

          }

          if(v.isSelect){
            total += v.count * v.price
          }

        })

        this.setData({
          shopcartData:shopcartData,
          total:total
        })

        this.allSelectSwatch()


      },
      fail:error=>{
        wx.hideLoading()
        console.log('云函数调用失败==>',error)
      }
    })
  },
  checkActive:function(e){

 
    var index = e.currentTarget.dataset.id


    this.updaShopcartIsSelect(this.data.shopcartData[index]._id,!this.data.shopcartData[index].isSelect)

    this.data.shopcartData[index].isSelect = !this.data.shopcartData[index].isSelect

    this.setData({
      shopcartData:this.data.shopcartData
    })

    //计算总金额
    this.sum()

    this.allSelectSwatch()

  },
  allSelect:function(){


    if(!this.data.allSelect){

      this.data.shopcartData.forEach(v=>{

        v.isSelect = true

        this.updaShopcartIsSelect(v._id,true)

      })

     }else{

      this.data.shopcartData.forEach(v=>{

        v.isSelect = false

        this.updaShopcartIsSelect(v._id,false)

      })


     }

    this.setData({
      shopcartData:this.data.shopcartData,
      allSelect:!this.data.allSelect
    })

    //计算总金额
    this.sum()

  },
  shopcartCount:function(e){


    wx.showLoading({
      title: '加载中...',
    })


    var id = e.currentTarget.dataset._id

    var index = e.currentTarget.dataset.index

    var rule = e.currentTarget.dataset.rule

    var type = e.currentTarget.dataset.type

    var count = this.data.shopcartData[index].count 

    if(type == "add"){

      this.data.shopcartData[index].count =  count + 1

    }else{

      if(count - 1 === 0){
        wx.hideLoading()
       
        return
      }

      this.data.shopcartData[index].count =  count - 1

    }


    wx.cloud.callFunction({
      name:'updataShopcart',
      data:{
        id:id,
        rule:rule,
        count:this.data.shopcartData[index].count
      },
      success:res=>{

        wx.hideLoading()

        console.log("res=>",res)

        this.setData({
          shopcartData:this.data.shopcartData
        })

        this.sum()

      },
      fail:error=>{
        wx.hideLoading()
        console.log("云函数调用失败error=>",error)
      }
    })


  },
  manage:function(){

    this.setData({
      isManage:!this.data.isManage
    })

  },

  //删除单个商品
  deleteShopcart:function(e){

    var id = e.currentTarget.dataset.id

    var index = e.currentTarget.dataset.index

    this.removeShopcart([id],index)

  },
  allDeleteShopcart:function(){

    wx.showLoading({
      title: '加载中...',
    })

    wx.cloud.callFunction({
      name:'remove_shopcart',
      success:res=>{
        wx.hideLoading()
        console.log('删除成功')
        this.setData({
          shopcartData:[]
        })
      },
      fail:error=>{
        wx.hideLoading()
        console.log('云函数调用失败==>',error)
      }
    })

  },
  //删除选中的购物车商品
  deleteIsSelect:function(){

    wx.showLoading({
      title:'加载中...'
    })

    var shopcartData = this.data.shopcartData

    var ids = []


    for(var i =0; i < shopcartData.length ; i++){

      if(shopcartData[i].isSelect){

        ids.push(shopcartData[i]._id)
      }

    }

    if(ids.length<1){
      wx.hideLoading()
      wx.showToast({
        title: '请选中要删除的商品',
        icon:'none',
      })
      return
    }

    this.removeShopcart(ids)


  },
  //删除购物车商品方法
  removeShopcart:function(ids,index){


    wx.showLoading({
      title: '加载中...',
    })

    wx.cloud.callFunction({
      name:'remove_shopcart_byid',
      data:{
        ids:ids,
      },
      success:res=>{

        wx.hideLoading()

        var shopcartData = this.data.shopcartData
        
        if(index !==undefined){

          shopcartData.splice(index,1)

        }else{

          ids.forEach(v=>{
      
            for(var i=0; i<shopcartData.length;i++){
      
              if(v == shopcartData[i]._id){
      
                shopcartData.splice(i,1)
              }
      
            }
      
          })

        }

        this.setData({
          shopcartData:shopcartData
        })

        this.sum()

        //购买车变零时回到管理页面状态
        if(this.data.shopcartData.length == 0){
          this.setData({isManage:false})
        }


      },
      fail:error=>{
        wx.hideLoading()
        console.log("云函数调用失败=>",error)
      }
    })


  },
  //计算总金额
  sum:function(){

    var total = 0
    this.data.shopcartData.forEach(v=>{
      if(v.isSelect){
        total+=v.count * v.price
      }
    })

    this.setData({
      total:total
    })


  },
  bay:function(){

    var ids = []

    this.data.shopcartData.forEach(v=>{
      if(v.isSelect){
        ids.push(v._id)
      }
    })

    if(ids.length == 0){

      wx.showToast({
        title: '请选中要购买的商品',
        icon:'none',
      })

      return
    }

    wx.navigateTo({
      url: '../commit/commit?id='+ids.join("@"),
    })

  },
  updaShopcartIsSelect(id,isSelect){

    wx.showLoading({
      title: '加载中...',
      icon:'none'
    })
    wx.cloud.callFunction({
      name:'update_shopcart_isSelect',
      data:{
        id:id,
        isSelect:isSelect
      },
      success:res=>{
        wx.hideLoading()
        console.log('更新成功==>',res)

        
      },
      fail:error=>{
        wx.hideLoading()
        console.log("云函数调用失败==>",error)
      }
    })
  },
  //监听是否全选
  allSelectSwatch(){

    var len = this.data.shopcartData.length 

    var n = 0

    this.data.shopcartData.forEach(v=>{

      if(v.isSelect){
        n += 1
      }

    })

    if(n == 0){

      this.setData({
        allSelect:false
      })

    }else if(n == len){

      this.setData({
        allSelect:true
      })


    }else{

      this.setData({
        allSelect:false
      })

    }



  }
})